<?php

namespace app\command\task\YoPoint;

use app\model\BaseModel;
use app\model\device\DeviceBaseModel;
use Exception;
use Symfony\Component\Process\Process;
use think\console\Command;
use think\console\Input;
use think\console\Output;

/**
 * 同步友朋设备按月流水
 */
class YoPointBrandAsyncMonthTerminalProductJournal extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('同步友朋设备按月流水')
            ->setDescription('同步友朋设备按月流水');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $this->terminalProductJournalListSyancByMonth();
        } catch (Exception $e) {
            $this->output->writeln($e->getMessage());
        }
    }

    /**
     * 售货机流水记录按月同步
     * @return void
     * @throws Exception
     */
    private function terminalProductJournalListSyancByMonth()
    {
        $deviceModel = new DeviceBaseModel();
        $deviceModelWhere = [
            'data_source_from' => BaseModel::dataSourceFromYoPoint,
        ];
        $allDeviceList = $deviceModel
            ->getAllList($deviceModelWhere, 'id, uuid, name')
            ->data;
        if (empty($allDeviceList)) {
            $this->output->writeln('无设备');
            return;
        }

        $processFunc = function (array $command) {
            $process = new Process($command);
            $process->setTimeout(3600);
            return $process;
        };

        $processList = [];

        // 生成连续的月份
        $months = getMonthsRangeFromTimestamp(time(), 12);
        foreach ($allDeviceList as $value) {
            $deviceUUID = $value['uuid'];
            $this->output->writeln("device ID:" . $deviceUUID);
            foreach ($months as $monthRange) {
                $startDate = $monthRange['start_date'];
                $endDate = $monthRange['end_date'];
                $dateRange = "$startDate - $endDate";
                $this->output->writeln("dateRange:" . $dateRange);
                $runCommand = [
                    'php', 'think', 'yoPointBrandTerminalProductProcess', "$deviceUUID",
                    "$startDate", "$endDate"
                ];
                $processList[] = $processFunc($runCommand);
            }
        }

        if (!empty($processList)) {
            $this->output->writeln('开始异步进程');

            $chunkList = array_chunk($processList, 10);
            foreach ($chunkList as $key => $dealList) {
                $this->output->writeln("第" . ($key + 1) . "组开始");
                foreach ($dealList as $item) {
                    $item->start();
                    sleep(10);
                }
                foreach ($dealList as $item) {
                    $item->wait();
                    $this->output->writeln("子进程结束，退出码：" . $item->getExitCodeText());
                }
                sleep(60);
            }
        }
    }


}